package com.nengchuan.eic.nceconomy.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nengchuan.config.exception.NcException;
import com.nengchuan.eic.nceconomy.aspect.RequsetParamAop;
import com.nengchuan.eic.nceconomy.entity.vo.OssFileReseponseVO;
import com.nengchuan.eic.nceconomy.entity.vo.OssStsconfigResponseVO;
import com.nengchuan.eic.nceconomy.entity.vo.OssUploadAddFileResponseVO;
import com.nengchuan.eic.nceconomy.entity.vo.OssUploadAddFileVO;
import com.nengchuan.eic.nceconomy.fegin.ProcessFeignFileService;
import com.nengchuan.eic.nceconomy.util.FileNameUtils;
import com.nengchuan.model.model.WrappedResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.alibaba.nacos.client.config.impl.ServerListManager.log;

/**
 * 功能描述:
 *
 * @Author: liurui
 * @Date: 2020/4/22 0022 下午 4:23
 */
@Service
public class OssService {

    @Autowired
    private ProcessFeignFileService processFeignFileService;
    private final static Logger logger = LoggerFactory.getLogger(OssService.class);
    /**
     * 上传文件并获取ossid
     * @param file
     * @return
     * @throws IOException
     */
    public Long uploadByOss(MultipartFile file) throws IOException {
        final String serviceName = "eic-nceconomy-service";
        final String bisiName = "nceconomy";
        WrappedResult<OssStsconfigResponseVO> eicresult = getOssInfo(serviceName, bisiName);
        logger.info("获取oss信息----"+new ObjectMapper().writeValueAsString(eicresult));
        OssStsconfigResponseVO eic = eicresult.getData();

        final String fileSuffixName = FileNameUtils.getSuffix(file.getOriginalFilename());
        final String fileNameWithUUID = FileNameUtils.getFileName(file.getOriginalFilename());
        final String endpoint = eic.getEndpoint();
        final String accessKeyId = eic.getAccessKeyId();
        final String accessKeySecret = eic.getAccessKeySecret();
        final String pathName = eic.getPathName()+fileNameWithUUID;
        final String bucket = eic.getBucket();
        final String stsToken = eic.getStsToken();
        logger.info("上传oss信息----endpoint:{},,bucket:{},pathName:{}",endpoint,bucket,pathName);
        try{
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret,stsToken);
            PutObjectResult putObjectResult = ossClient.putObject(bucket, pathName, file.getInputStream());
            ossClient.shutdown();

        }catch (Exception e){
            throw new NcException("上传文件失败。");
        }

        WrappedResult<OssUploadAddFileResponseVO> ossUploadAddFileResponseVOWrappedResult = ossUpload(file.getOriginalFilename(), serviceName, fileSuffixName, pathName, bucket);
        return  ossUploadAddFileResponseVOWrappedResult==null?null:ossUploadAddFileResponseVOWrappedResult.getData().getId();

    }

    public WrappedResult<OssUploadAddFileResponseVO> ossUpload(String fileName, String serviceName, String fileSuffixName, String pathName, String bucket) {
        OssUploadAddFileVO ossUploadAddFileVO =new OssUploadAddFileVO();
        ossUploadAddFileVO.setFileName(fileName);
        ossUploadAddFileVO.setPath(pathName);
        ossUploadAddFileVO.setServerName(serviceName);
        ossUploadAddFileVO.setSuffix(fileSuffixName);
        ossUploadAddFileVO.setFileSize(0);
        ossUploadAddFileVO.setBucketName(bucket);

        WrappedResult<OssUploadAddFileResponseVO> ossUploadAddFileResponseVOWrappedResult=null;
        try{
            logger.info("获取ossId----"+new ObjectMapper().writeValueAsString(ossUploadAddFileVO));
            ossUploadAddFileResponseVOWrappedResult = processFeignFileService.ossUploadAddFile(ossUploadAddFileVO);
        }catch (Exception e){
            logger.error("获取ossId异常，原因:{}",e.getMessage());
        }
        return ossUploadAddFileResponseVOWrappedResult;
    }

    public WrappedResult<OssStsconfigResponseVO> getOssInfo(String serviceName, String bisiName) {
        WrappedResult<OssStsconfigResponseVO> eicresult = new WrappedResult<>();

        try{
            eicresult	 = processFeignFileService.getstsconfig(serviceName, bisiName);
        }catch (Exception e){
            logger.error("oss上传文件异常,原因:{}",e.getMessage());
        }
        return eicresult;
    }

    /**
     * 批量获取文件
     * @param ids
     * @return
     * @throws Exception
     */
    public WrappedResult<List<OssFileReseponseVO>> getFilesFromOssByIds(List<Long> ids) throws Exception {
        return processFeignFileService.findByIds(ids,"h_220");
    }

    /**
     * 获取文件
     * @param id
     * @return
     * @throws Exception
     */
    public WrappedResult<OssFileReseponseVO> getFilesFromOssById(Long id) throws Exception {
        return processFeignFileService.findById(id,"h_220");
    }
}
